/** @file */ 

#ifndef USART_H_
#define USART_H_

#include "Utilities.h"
#include "error.h"

#ifndef F_CPU2
	// Define the clock speed of the CPU
	#define F_CPU2 8000000
#endif
#ifndef BAUDRATE
	// Define the Baudrate for the USART
	#define BAUDRATE 38400
#endif

#define UBRR_VAL ((F_CPU2+BAUDRATE*8)/(BAUDRATE*16)-1)
#define BAUD_REAL (F_CPU2/(16*(UBRR_VAL+1)))     // Real Baudrate
#define BAUD_ERROR ((BAUD_REAL*1000)/BAUDRATE) // Error in per mille

#if ((BAUD_ERROR<990) || (BAUD_ERROR>1010))
#error Systematic error of Baudrate higher as 1 % and therefore to high!
#endif

/**
 * Initializes the USART controller for future use. 
 * The frame format defined for USART communication consists of
 * eight data bits, a parity bit (even) and two stop bits                                                         
 */
void init_USART();

/**
 * Transmits a single byte by using USART                                                          
 */
void send_byte_USART(uint8_t byte);

/**
 * Transmits the given command, followed by the specified parameters.                                                       
 */
void send_cmd_USART(command_t cmd, uint8_t* params, uint8_t length);

/**
 * This function blocks until a byte can be received from the USART
 * controller  
 * \return Returns 0 at success. Otherwise -1 will be returned and errno will be set to one of these values: \n
	FRAME_ERROR_USART	if a frame error occurred; \n
	PARITY_ERROR_USART	if a parity error occurred; \n
	OVERFLOW_USART	    if an overflow occurred                                                  
 */
uint8_t receive_byte_USART(uint8_t* byte);

/**
 * This function receives the specified amount of bytes and stores them at the position pointed at by data
 * \return Returns 0 at success. Otherwise -1 will be returned and errno will be set to one of these values:\n
	FRAME_ERROR_USART	if a frame error occurred; \n
	PARITY_ERROR_USART	if a parity error occurred; \n
	OVERFLOW_USART	    if an overflow occurred                                                                  
 */
uint8_t receive_cmd_results_USART(uint8_t* data, int length);



#endif /* USART_H_ */